package online.longzipeng.cinemasys.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import online.longzipeng.cinemasys.common.result.ResponseEnum;
import online.longzipeng.cinemasys.common.result.Result;
import online.longzipeng.cinemasys.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * @Author: lzp
 * @Date: 2021/2/12 11:27
 */
@RestController
@RequestMapping("/file")
@Api(value = "文件相关接口",description = "文件相关接口",tags = "文件相关接口")
public class FileController {

    @Autowired
    FileService fileService;

    /**
     * 文件上传
     * @param file
     * @param module
     * @return
     * @throws IOException
     */
    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public Result upload(
            @ApiParam(value = "文件", required = true)
            @RequestParam("file") MultipartFile file,
            @ApiParam(value = "指定上传的目录", required = true)
            @RequestParam("module") String module) throws IOException {

        // 获得上传文件的 InputStream
        InputStream inputStream = file.getInputStream();
        // 获得上传文件的名字
        String originalFilename = file.getOriginalFilename();
        String uploadUrl = fileService.upload(inputStream, "imgs/"+module, originalFilename);

        //返回对象
        return new Result(ResponseEnum.SUCCESS,uploadUrl);
    }

    @ApiOperation("上传头像")
    @PostMapping("/upload_to_avatars")
    public Result uploadToAvatar(
            @ApiParam(value = "文件", required = true)
            @RequestParam("file") MultipartFile file) throws IOException {
        // 获得上传文件的 InputStream
        InputStream inputStream = file.getInputStream();
        // 获得上传文件的名字
        String originalFilename = file.getOriginalFilename();
        String uploadUrl = fileService.upload(inputStream, "imgs/avatars", originalFilename);

        //返回对象
        return new Result(ResponseEnum.SUCCESS,uploadUrl);
    }

    @ApiOperation("上传图标")
    @PostMapping("/upload_to_icons")
    public Result uploadToIcon(
            @ApiParam(value = "文件", required = true)
            @RequestParam("file") MultipartFile file) throws IOException {
        // 获得上传文件的 InputStream
        InputStream inputStream = file.getInputStream();
        // 获得上传文件的名字
        String originalFilename = file.getOriginalFilename();
        String uploadUrl = fileService.upload(inputStream, "imgs/icons", originalFilename);

        //返回对象
        return new Result(ResponseEnum.SUCCESS,uploadUrl);
    }

}
